const websocket_start = function (id) {
    let socket_;
    let heartbeatInterval; // 心跳检测的定时器
    let reconnectTimeout;  // 重连的定时器

    const connect = function () {
        socket_ = new WebSocket(`ws://127.0.0.1:8001/date_socket/ws/${id}`);

        socket_.onopen = function () {
            startHeartbeat();
        };

        socket_.onmessage = function (event) {
            // console.log("Message from server:", event.data);

            // 如果收到的是心跳响应（如 "pong"），可以在这里处理
            if (event.data === "pong") {
                // console.log("Heartbeat response received");
            }
        };
        
        socket_.onclose = function () {
            // console.log("WebSocket is closed now.");
            stopHeartbeat(); // 停止心跳检测
            attemptReconnect(); // 尝试重新连接
        };

        socket_.onerror = function (event) {
            // console.error("WebSocket error observed:", event);
            socket_.close(); // 触发关闭事件以自动重连
        };
    };

    const startHeartbeat = function () {
        if (heartbeatInterval) {
            clearInterval(heartbeatInterval);
        }
        heartbeatInterval = setInterval(function () {
            if (socket_.readyState === WebSocket.OPEN) {
                // console.log("Sending heartbeat...");
                socket_.send("ping"); // 发送心跳包
            } else {
                // console.warn("WebSocket is not open, stopping heartbeat.");
                stopHeartbeat(); // 停止心跳检测
            }
        }, 20000); // 每 10 秒发送一次心跳
    };

    const stopHeartbeat = function () {
        if (heartbeatInterval) {
            clearInterval(heartbeatInterval);
            heartbeatInterval = null;
        }
    };

    const attemptReconnect = function () {
        if (reconnectTimeout) {
            clearTimeout(reconnectTimeout);
        }
        reconnectTimeout = setTimeout(function () {
            // console.log("Attempting to reconnect...");
            connect(); // 尝试重新连接
        }, 5000); // 5 秒后尝试重新连接
    };

    connect(); // 初始化连接
};
export { websocket_start}
